<template>
  <div class="callarea" v-loading="loading">
    <div v-show="!switchTem">
      <div class="top">
        <div class="search">
          <div class="contition">
            <div class="wrap_time">
              <date-time type="other_half_hour" @changeType="changeType" @changeDateS="childTimeChange" :query="query" @isFold="isShowFold" :isTimePeriod="true" :isOther="true"></date-time>
              <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button></div>
            <div class="clear"></div>
            <div class="wrap_drop">
              <unfold :isShow="isFold" :title="[]">
                <template slot="unfoldSlot">
                  <div class="serve">
                    <span class="colo">{{$t('monitor.serviceNum')}}：</span>
                    <servicesNoFilter  v-if="isViewShow" :serviceNos = "serviceNos" :checkedNos = "checkedServiceNos" @serveNoFilterChange = "serveNoFilterChange" style="width:220px;display: inline-block;margin-right:20px;"></servicesNoFilter>
                    <el-checkbox v-model.trim="checkAll" @change="handleServiceNosCheckAll">{{$t('public.checkAll')}}</el-checkbox><el-checkbox v-model.trim="query.delete_call_serverNo">{{$t('report.deletedServe')}}</el-checkbox>
                    <el-checkbox-group v-model.trim="checkedServiceNos" @change="handleServiceNosCheck">
                      <div class="serviceDisplayWrap" v-for="(number, index) in serviceNos" :key="index">
                        <el-checkbox :label="number.Exten" :value="number.Exten">{{number.Exten}}<span v-if="number.DisplayName">[<span :title="number.DisplayName" class="serviceDisplayName ellipsis">{{number.DisplayName}}</span>]</span></el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </div>
                  <div class="serve serve1">
                    <span class="pro colo">{{$t('public.province')}}：</span>
                    <el-checkbox :indeterminate="isIndeterminate1" v-model.trim="checkAll1" @change="handleProvincesCheckAll">{{$t('public.checkAll')}}</el-checkbox>
                    <el-checkbox-group v-model.trim="checkedProvinces" @change="handleProvincesCheck">
                      <el-checkbox v-for="(province, index) in provinces" :key="index" :label="province" :name="province">{{province}}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </template>
              </unfold>
            </div>
          </div>
        </div>
        <affix :label="$t('report.callInAreaSurvey')"></affix>
        <div class="situation">
          <div class="wrap_pro">
            <div class="call_all">
              <span>{{$t('monitor.inCallSum')}}</span>
              <span class="all_num">{{callInAll}}</span>
            </div>
            <div class="wrap_top" v-show="serveNumData.length !== 0">
              <span>{{$t('report.callInTopPro')}}</span>
              <ul>
                <li v-for="(item, index) in situation" :key="index">
                  <span class="sum_name">{{item.name}}</span>
                  <span class="sit_num">{{item.value}}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <affix :label="$t('report.relaycallDis')"></affix>
        <div class="clear"></div>
      </div>
      <div class="tab" :id="id">
        <div class="export">
          <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>
            <!-- <el-button class="primary_btn fr report_excel_btn"
              v-if="$store.getters.exportFromEnd"
              v-on:click.stop="exportExcel"
            >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->
          <el-tooltip class="item" content="点击此处可导出时间范围下每日的地区分布数据。注：当您选择的时间范围超过一个月时，详情只支持导出近一个月的详细数据。" effect="dark" placement="bottom">
            <el-button class="primary_btn fr" style="margin: 0 10px 0 0" v-show="isShowDetailExport" v-on:click.stop="exportDetailExcel(true)">{{$t('report.exportDetailXls')}}
              <span class="tip"><i class="iconfont icon-tixingweizhi" style="border: none;font-size: 10px;color: #459ae9;"></i></span>
            </el-button>
          </el-tooltip>
            <el-button class="primary_btn fr report_excel_btn"
              v-on:click.stop="exportXlsx"
            >{{$t('report.exportXls')}}</el-button>
          <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                <p style="color: #ccc;
    margin: 5px 0;
    font-size: 12px;">{{ $t('report.callHint') }}</p>
                {{$t('report.callIvr')}}<br>
                {{$t('report.callAnswerNum')}}<br>
                {{$t('report.callMesLeaveNum')}}<br>
                {{$t('report.callRingNotAnswerNum')}}<br>
                {{$t('report.callQueueUpNum')}}<br>
                {{$t('report.callBlankRedNum')}}<br>
                {{$t('report.callAllHappenNum')}}<br>
                {{$t('report.callTotalNum')}}<br>
                9.{{$t('report.IncomingTimeLength')}}<br>
                10.{{$t('report.IncomingRingingTimeLength')}}<br>
                11.{{$t('report.CustomerFastHangUp')}}
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="serveNumData" :sum="sum" :config="headOptions.Config" @proName ="name"> </report-table>
      </div>
      <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
        <span>{{$t('report.reportExportTipTitle')}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
          <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
        </span>
      </el-dialog>
      <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_relay_area" v-on:close="close"></header-option>
    </div>
    <!-- 传递城市名 查询条件 服务号信息 原始时间数据 渲染时间组件用的 -->
    <openrelayarea ref="myChild" :parentDateType="dateType" :cityName = "{cityName, queryOne, checkedServiceNos, dateSource, switchTem}" @flag="show" v-show="switchTem"></openrelayarea>
  </div>
</template>
<script>
  import dateTime from '../base/dateDrill.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import headerOption from '../base/headerOption.vue'
  import reportTable from '../base/drillInto.vue'
  import openrelayarea from './OpenRelayArea.vue'
  import {exportReportPdf, checkTime, searchTime, headOptionsToXlsxHeaders, reportAreaProvince} from '@/utils/reportUtils.js'
  import {getCache, deepClone, getCallTimeLength, optionTimeTypeCheck} from '@/utils/m7Utils.js'
  import servicesNoFilter from '../base/servicesNoFilter.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import {sortBy} from 'lodash'
  export default {
    name: 'callarea',
    data () {
      return {
        dateType: 'day',
        isFold: false, // 是否展示搜索条件
        situation: [], // 概况渲染数据
        callInAll: 0, // 呼入总数
        dateSource: {}, // 钻入需要的数据
        loading: false, // 查询时展示加载的开关
        isViewShow: false, // 服务号筛选功能开关
        id: 'call_report_relay_area', // 查询id
        resData: [], // 返回数组暂存
        query: { // 查询条件时间信息等
          reportType: '',
          delete_call_serverNo: false,
          delete_call_serverNos: ''
        },
        cityName: '', // 钻入传的城市名
        switchTem: false, // 是否显示当前组件或钻入组件开关
        checkAll: true, // 服务号全选绑定值
        checkAll1: true, // 省份全选绑定值
        checkedServiceNos: [], // 服务号绑定值
        checkedProvinces: [], // 省份绑定值
        headOptionsShow: {}, // 配置表头数据
        headOptions: { // 表头数据
          Config: []
        },
        isShow: false, // 是否展示配置表头开关
        dialogVisible: false, // 导出pdf弹窗开关
        serviceNos: [], // 服务号数据
        provinces: reportAreaProvince, // 省份数据
        isIndeterminate: false, // 全选样式调控值
        isIndeterminate1: false, // 全选样式调控值
        sum: [], // 表格合计数据
        serveNumData: [], // 表格table除合计数据
        queryOne: {} // 子组件查询数据
      }
    },
    computed: {
      // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['week', 'month', 'other_half_hour']
        return type.includes(this.dateType)
      },
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      }
    },
    methods: {
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      // 钻入需要渲染的原始时间数据, 子组件传过来的方法
      childTimeChange (obj) {
        this.dateSource = obj
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 钻入的子组件传上来的方法 展示当前页
      show () {
        this.switchTem = false
      },
      // 渲染服务号和省
      condition () {
        let self = this
        this.provinces.forEach(function (item) {
          if (self.checkedProvinces.indexOf(item) >= 0) {
            self.query['Province_' + item] = true
          } else {
            self.query['Province_' + item] = false
          }
        })
        self.serviceNos.forEach(function (item) {
          if (self.checkedServiceNos.indexOf(item.Exten) >= 0) {
            self.query['ServiceNo_' + item.Exten] = true
          } else {
            self.query['ServiceNo_' + item.Exten] = false
          }
        })
      },
      // 渲染钻入组件的查询条件
      name (name) {
        this.cityName = name
        // 判断服务号是否为空
        // if (this.checkedServiceNos.length === 0 && this.query.delete_call_serverNo === false) {
        //   this.open3()
        // }
        // // 判断省是否为空
        // if (this.checkedProvinces.length === 0) {
        //   this.open2()
        // }
        // 初始化查询条件
        this.condition()
        let myQuery = deepClone(this.query)
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.relayAreaCityCurrentProvince = ''
        this.queryOne = myQuery
        this.switchTem = true
        // let self = this
        // setTimeout(function() {
        //   self.$refs.myChild.search1()
        // }, 0)
        this.$nextTick(() => {
          this.$refs.myChild.search1()
        })
      },
      // 获取新的表格数据ServeNumData，抽取共同
      getServeNumDataAndSum (isExport) {
        let headOptions = this.headOptions
        let tempData = this.resData
        let sum = {Province: this.$t('report.total')}
        if (!tempData || tempData.length === 0) {
          this.callInAll = 0
          return {
            serveNumData: [],
            sum: []
          }
        }
        tempData = sortBy(this.resData, (item) => {
          return -item.AccessCount
        })
        // 计算合计
        for (let i in tempData) {
          let item = tempData[i]
          if (!isExport) {
            // 渲染概况 渲染前五得省份
            if (i < 5) {
              this.situation.push({name: item._id, value: item.AccessCount})
            }
          }
          for (let j in item) {
            if (sum[j] === undefined) {
              sum[j] = 0
            }
            if (j !== 'Province') {
              sum[j] += item[j]
            }
          }
          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getCallTimeLength(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            }
          })
        }
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            sum[option.name] = getCallTimeLength(sum[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            sum[option.name] = Math.round(sum[option.name]) + 's'
          }
        })
        if (!isExport) {
          // 渲染概况
          this.callInAll = sum.AccessCount || 0
        }
        // 使table开始渲染的时间按顺序排列
        return {
          serveNumData: tempData,
          sum: [sum]
        }
      },
      // 获取查询条件
      getSearchQueryData () {
        // 判断服务号是否为空
        if (this.checkedServiceNos.length === 0 && this.query.delete_call_serverNo === false) {
          this.open3()
          return
        }
        // 判断省是否为空
        if (this.checkedProvinces.length === 0) {
          this.open2()
          return
        }
        // 优化查询条件
        this.condition()
        // 初始化查询条件
        let data = {
          reportType: 'call_report_relay_area',
          account: this.$store.state.session.user.account
        }
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = null
          if (this.dateType === 'week') { // 周报允许到天并改为other
            myQuery.timeType = 'other'
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        // 转换timeType查询条件
        this.query.timeType = myQuery.TimeType
        myQuery.relayAreaCityCurrentProvince = ''
        data.query = myQuery
        delete myQuery.normalEndTime
        delete myQuery.normalStartTime

        return data
      },
      // 查询方法
      search () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }

        this.situation = []
        this.loading = true
        this.$store.dispatch('queryCallRelayAreaReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.headOptions = optionTimeTypeCheck(res.tableHeader)
          this.resData = res.data
          let {serveNumData, sum} = this.getServeNumDataAndSum(false)
          this.sum = sum
          this.serveNumData = serveNumData
          this.loading = false
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }
        this.loading = true
        this.$store.dispatch('queryCallRelayAreaReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.resData = res.data
          var headOptions = res.tableHeader
          this.loading = false
          let {serveNumData, sum} = this.getServeNumDataAndSum(true)
          if (serveNumData.length === 0) {
            sum = []
          }

          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var tableData = serveNumData.concat(sum)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.callReportRelayArea') + timeStamp)
        })
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.callReportRelayArea') + searchTime(this.query), id: this.id})
      },
      exportDetailExcel () {
        this.condition()
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = null
          if (this.dateType === 'week') { // 周报允许到天并改为other
            myQuery.timeType = 'other'
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          } else {
            message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          }
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 转换timeType查询条件
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        myQuery.reportType = 'call_report_relay_area'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'ReportRelayAreaExport'
        myQuery.user = this.$store.state.session.user._id
        let data = {
          Method: 'exportIncomingDistrictDetails',
          Query: myQuery
        }
        this.$store.dispatch('exportCallRelayAreaReport', data).then(() => {
        })
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        this.condition()
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
           // 校验类型与时间
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 转换timeType查询条件
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        myQuery.reportType = 'call_report_relay_area'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'ReportRelayAreaExport'
        myQuery.user = this.$store.state.session.user._id
        let data = {
          Method: 'ReportRelayAreaExport',
          Query: myQuery
        }
        this.$store.dispatch('exportCallRelayAreaReport', data).then(() => {
        })
      },
      // 配置表头
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_relay_area').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 判断查询条件是否为空
      open3 () {
        this.$message.error(this.$t('report.searchBathnos'))
      },
      open2 () {
        this.$message.error(this.$t('report.searchProvince'))
      },
      // 全选，参考饿了么
      handleServiceNosCheckAll (event) {
        this.checkedServiceNos = []
        if (this.checkAll === true) {
          this.serviceNos.forEach((i) => {
            this.checkedServiceNos.push(i.Exten)
          })
        }
      },
      // 选择服务号判断是否勾选全选
      handleServiceNosCheck () {
        if (this.checkedServiceNos.length === this.serviceNos.length) {
          this.checkAll = true
        } else {
          this.checkAll = false
        }
      },
      // 点击全选触发的方法
      handleProvincesCheckAll (event) {
        this.checkedProvinces = this.checkAll1 ? this.provinces : []
        this.isIndeterminate1 = false
      },
      // 点击选择省份触发的方法 参数选择省份值[]
      handleProvincesCheck (value) {
        let checkedCount = value.length
        this.checkAll1 = checkedCount === this.provinces.length
        this.isIndeterminate1 = checkedCount > 0 && checkedCount < this.provinces.length
      },
      //      服务号筛选  后加功能
      serveNoFilterChange (val) {
        this.checkedServiceNos = val
        this.handleServiceNosCheck()
      }
    },
    watch: {
    },
    components: {
      affix,
      unfold,
      dateTime,
      headerOption,
      reportTable,
      openrelayarea,
      servicesNoFilter
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'serviceNo', loadFromServer: true}).then(() => {
        this.serviceNos = getCache('serviceNo')
        this.isViewShow = true
        this.handleServiceNosCheckAll()
        this.handleProvincesCheckAll()
        this.search()
      })
    },
    mounted () {
//      this.appendTfoot()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .callarea
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid #459ae9
      text-align center
      line-height 15px
      border-radius 50%
    margin 0px 0 0 6px
    .tab
      margin-top 0
    .el-checkbox-group
      margin-left 40px
      .el-checkbox
        width 76px
        margin-left 12px
        &:nth-child(1)
          padding-left 12px
          margin-left 0
    .serve1
      .el-checkbox
        width 90px
      .tex
        margin-left 10px
        cursor pointer
    .serviceDisplayWrap
      display inline-block
      width 170px
      .serviceDisplayName
        max-width 48px
        display inline-block
        position relative
        top 5px

</style>
